package code.easy.paging

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.PagingSource
import androidx.paging.cachedIn
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow

/**
 * 配合Room数据库使用
 */
open class EasyRoomPagingSource<Key : Any, Value : Any>(
    viewModelScope: CoroutineScope,
    pageSize: Int = 20,
    prefetchDistance: Int = 3,
    pagingSourceFactory: () -> PagingSource<Key, Value>
) {
    private val pager: Pager<Key, Value> = Pager(
        PagingConfig(
            pageSize = pageSize,
            prefetchDistance = prefetchDistance,
            enablePlaceholders = false
        ),
        pagingSourceFactory = pagingSourceFactory
    )

    open val flow: Flow<PagingData<Value>> = pager.flow.cachedIn(viewModelScope)

}